package com.gaojx.lang.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;

import java.util.Map;

/**
 * @author junxiang.gao
 * @since 2020/9/1
 */
public class BeanRegistrar implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        try {
            // 调用我们刚才的工具类，将扫描到的类注放到Map中
            // 这里的Map是包含 需要注入Bean（class）的小写类名，具体类型，看上图。
            // 包名URLConstants.PACKAGE_PATH
            Map<String, Class<?>> classMap = ClassScanUtil.getBeans("groovy/GroovyFileRule3.groovy");
            if (!classMap.isEmpty()) {
                classMap.forEach((key, value) -> {
                    System.out.println("=======>>>  正在加载 " + key + " —— " + value + "......  ");
                    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(value);
                    AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
                    registry.registerBeanDefinition(key, beanDefinition);
                });
            }
        } catch (ClassNotFoundException e) {
            System.out.println("初始化 Beans 异常");
            e.printStackTrace();
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
